package com.turman.networkdemo

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

/**
 * 本地cookie缓存策略
 */
internal class LocalCookieJar:CookieJar {
    private val cache:MutableList<Cookie> = mutableListOf<Cookie>()
    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val invalidCookies:MutableList<Cookie> = ArrayList()
        val validCookies:MutableList<Cookie> = ArrayList()

        for (cookie:Cookie in cache) {
            if (cookie.expiresAt < System.currentTimeMillis()) {
                invalidCookies.add(cookie)  //过期了
            } else if (cookie.matches(url)) {
                validCookies.add(cookie)
            }
        }

        cache.removeAll(invalidCookies) //清除过期的
        return validCookies
    }

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cache.addAll(cookies)
    }


}